<template>
  <el-card class="box-card">
    <!-- 添加按钮 -->
    <el-button type="primary" :icon="Plus" @click="showSaveDialog"
      >添加品牌</el-button
    >

    <!-- 表格 -->
    <el-table :data="trademarkList" border class="trademark-table">
      <el-table-column type="index" label="序号" align="center" width="60" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template #default="{ row }">
          <img :src="row.logoUrl" :alt="row.tmName" class="trademark-img" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template #default="{ row }">
          <el-tooltip content="编辑品牌" placement="top" effect="light">
            <el-button
              size="small"
              type="warning"
              :icon="Edit"
              @click="showUpdateDialog(row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除品牌" placement="top" effect="light">
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="delTrademark(row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout="prev, pager, next, jumper, total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 模态框 -->
    <!-- :title动态展示是添加品牌还是修改品牌 -->
    <el-dialog
      v-model="visible"
      :title="`${trademarkFormData.id ? '修改' : '添加'}品牌`"
    >
      <!-- 表单 -->
      <el-form
        ref="trademarkFormRef"
        :model="trademarkFormData"
        :rules="trademarkFormRules"
        label-width="90px"
      >
        <!-- 表单项 -->
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            v-model="trademarkFormData.tmName"
            class="trademark-input"
          />
        </el-form-item>

        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 图片上传框 -->
          <el-upload
            class="avatar-uploader"
            action="/app-dev/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkFormData.logoUrl"
              :src="trademarkFormData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

            <template>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过200kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "MyTrademark",
};
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, FormInstance, FormRules } from "element-plus";
import { ref, onMounted, reactive } from "vue";
import {
  getTrademarkListApi,
  saveTrademarkApi,
  updateTrademarkApi,
  removeTrademarkApi,
} from "@/api/product/trademark";
import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/model/trademarkModel";

// 模态框显示&隐藏的标识
const visible = ref(false);
// 点击删除：

const delTrademark = (row: TrademarkItem) => {
  ElMessageBox.confirm("确定删除吗？", "删除", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await removeTrademarkApi(row.id);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      // 重新获取数据，刷新列表
      getTrademarkList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

/* ------------------------------------------------------ */
// 点击编辑按钮的功能，弹出模态框：
const showUpdateDialog = (row: TrademarkItem) => {
  visible.value = true;
  // 将当前行的信息赋值给表单中对应的属性，一点击编辑就显示对应的数据
  trademarkFormData.tmName = row.tmName;
  trademarkFormData.logoUrl = row.logoUrl;
  trademarkFormData.id = row.id;
  trademarkFormRef.value?.clearValidate(); // 清空表单校验结果
};

// 点击添加数据按钮时需要清空模态框内容
const showSaveDialog = () => {
  visible.value = true;
  trademarkFormData.tmName = "";
  trademarkFormData.logoUrl = "";
  trademarkFormData.id = 0;
  trademarkFormRef.value?.clearValidate(); // 清空表单校验结果
};
// 接下来定义请求接口函数，如果有id就是修改数据，没有就是增加数据

// ref语法，用来获取组件实例对象
const trademarkFormRef = ref<FormInstance>();
// 表单数据
const trademarkFormData = reactive({
  // 定义表单数据名称：要求发送请求携带参数名称一致，要和数据源保证一致
  tmName: "",
  logoUrl: "",
  id: 0,
});

// 定义表单校验规则: 规则名称，必须和表单数据名称一致
const trademarkFormRules = reactive<FormRules>({
  tmName: [
    {
      required: true,
      message: "请输入品牌名称",
      trigger: "blur",
    },
  ],
  logoUrl: [
    {
      required: true,
      message: "请输入品牌LOGO",
      trigger: "blur",
    },
  ],
});

// 触发表单校验
const submitForm = () => {
  // 触发表单校验
  // value?.validate 可选链语法，value有值就会调用validate，每值就不会调用
  trademarkFormRef.value?.validate(async (valid) => {
    // valid为true，代表表单校验通过
    if (valid) {
      // 表单校验通过，发送请求添加数据(更新服务器数据)
      const { tmName, logoUrl, id } = trademarkFormData;
      if (id) {
        // 如果有id，就是修改数据
        await updateTrademarkApi({ tmName, logoUrl, id });
      } else {
        // 没有id，就是添加数据
        await saveTrademarkApi(tmName, logoUrl);
      }
      // 关闭模态框
      visible.value = false;
      // 清空表单数据
      trademarkFormRef.value?.resetFields();
      // 提示用户添加/修改成功
      ElMessage.success(`${id ? "修改成功" : "添加成功"}`);
      // 重新获取数据，也就是刷新页面(更新客户端数据)
      getTrademarkList();
    }
  });
};

// 图片上传成功触发的函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // 上传成功，更新表单数据
  trademarkFormData.logoUrl = response.data;
};

// 图片上传之前触发的函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const typeFiles = ["image/jpeg", "image/jpg", "image/pnj"];
  // 如果图片不是指定类型，则提示错误
  if (!typeFiles.includes(rawFile.type)) {
    ElMessage.error("上传图片格式不正确");
    return false;
    // 限制上传图片大小
  } else if (rawFile.size / 1024 > 500) {
    ElMessage.error("上传图片大小不能超过500k");
    return false;
  }
  // 符合要求后上传
  return true;
};
// 表格每列的数据
const trademarkList = ref<TrademarkList>([]);

// 当前页码
const currentPage = ref(2);

// 每页条数
const pageSize = ref(3);

// 总条数
const total = ref(0);

// 封装函数，发送请求，获取数据
const getTrademarkList = async () => {
  const result = await getTrademarkListApi(currentPage.value, pageSize.value);
  trademarkList.value = result.records;
  total.value = result.total;
};
// 一上来就请求数据展示列表
onMounted(() => {
  getTrademarkList();
});
// 当page-size发生变化时触发，他会将最新的pageSize传递过来
const handleSizeChange = (newPageSize: number) => {
  // 更新pageSize，然后重新请求数据
  pageSize.value = newPageSize;
  getTrademarkList();
};
// 当currentPage发生变化时触发，也就是当前页变化时,他会将最新的currentPage传递过来
const handleCurrentChange = (newCurrentPage: number) => {
  //  更新currentSize,然后重新请求数据
  currentPage.value = newCurrentPage;
  getTrademarkList();
};
</script>

<style scoped>
.trademark-table {
  margin: 20px 0;
}
.trademark-img {
  width: 150px;
  height: 100px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.trademark-input {
  width: 60%;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
